<template>
  <div class="bigbox">
    <!-- 盒子头部 -->
    <div class="titlebox">
      <el-form
        :model="form"
        label-position="left"
        label-width="80px"
        onsubmit="event.preventDefault();"
      >
         <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                      v-model="form.orgNo"
                      @updateModelValue="change"
                      :optionlist="qiyelist"
                      :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
                    ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="display: flex;margin-top: 4px;">
              <el-radio-group v-model="form.periodType" size="small" style="margin-right: 20px;">
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
              <template v-if="form.periodType == '年'">
                <el-date-picker
                  v-model="form.value3"
                  style="flex: 1;"
                  type="year"
                  size="small"
                  value-format="yyyy"
                  placeholder="选择年"
                >
                </el-date-picker>
              </template>
              <template v-else>
                <el-date-picker
                  v-model="form.value2"
                  type="month"
                  style="flex: 1;"
                  size="small"
                  value-format="yyyy-MM"
                  placeholder="选择月"
                >
                </el-date-picker>
              </template>
          </el-col>
          <el-col :span="13" style="text-align: right;">
            <el-form-item label="">
              <el-button size="small" type="primary" @click="submits">查 询</el-button>
            </el-form-item>
          </el-col>
         </el-row>
      </el-form>
    </div>
    <!-- 盒子主体 -->
    <div class="bodybox">
      <!-- 表格饼图区域 -->
      <div class="table">
        <div class="paiming">
          <div class="item">
            <div class="itag jian">
              <div class="icon"><i class="iconfont icon-fadianliang"></i> </div>
              <div class="name tabs">尖段电量</div>
              <div class="num name">{{arrtotal.epowerJsd}}kWh,{{(arrtotal.epowerJsd/arrtotal.epowerTotal*100)?(arrtotal.epowerJsd/arrtotal.epowerTotal*100).toFixed(2):''}}%
              </div>
            </div>
            <div class="itag feng">
              <div class="icon"><i class="iconfont icon-fadianliang"></i> </div>
              <div class="name tabs">峰段电量</div>
              <div class="num name">{{arrtotal.epowerFsd}}kWh,{{(arrtotal.epowerFsd/arrtotal.epowerTotal*100)?(arrtotal.epowerFsd/arrtotal.epowerTotal*100).toFixed(2):''}}%</div>
            </div>
          </div>
          <div class="item">
            <div class="itag ping">
              <div class="icon"><i class="iconfont icon-fadianliang"></i> </div>
              <div class="name tabs">平段电量</div>
              <div class="num name">{{arrtotal.epowerPsd}} kWh,{{(arrtotal.epowerPsd/arrtotal.epowerTotal*100)?(arrtotal.epowerPsd/arrtotal.epowerTotal*100).toFixed(2):''}}%</div>
            </div>
            <div class="itag gu">
              <div class="icon"><i class="iconfont icon-fadianliang"></i> </div>
              <div class="name tabs">谷段电量</div>
              <div class="num name">{{arrtotal.epowerGsd}}kWh,{{(arrtotal.epowerGsd/arrtotal.epowerTotal*100)?(arrtotal.epowerGsd/arrtotal.epowerTotal*100).toFixed(2):''}}%</div>
            </div>
          </div>
        </div>
        <div class="echarts" ref="binecharts"></div>
      </div>
      <div class="zhuecharts" ref="zhuecharts"></div>
      <div class="biao">
      <!-- 头部右侧 -->
      <div style="display: flex; justify-content: space-between;margin: 20px 0;">
        <div>企业电量分析</div>
        <div class="title">
          <button class="button" @click="daochu">导出</button>
          <!-- 列表刷新 -->
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <span @click="shuaxin"
              ><i class="el-icon-refresh-right" style="cursor: pointer"></i
            ></span>
          </el-tooltip>
          <!-- 调节表格密度 -->
          <el-dropdown trigger="click" @command="command">
            <span class="el-dropdown-link">
              <el-tooltip
                class="item"
                effect="dark"
                content="密度"
                placement="top"
              >
                <span class="item"
                  ><i class="el-icon-d-caret" style="cursor: pointer"></i
                ></span>
              </el-tooltip>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="默认">默认</el-dropdown-item>
              <el-dropdown-item command="中等">中等</el-dropdown-item>
              <el-dropdown-item command="紧凑">紧凑</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
        <template>
          <el-table
            :data="tableData"
            :size="iissize"
            border
            :header-cell-style="{
              'text-align': 'center',
              background: '#f5f5f5'
            }"
            height="calc(100% - 1px)"
            highlight-current-row
            v-loading="loading"
            style="width: 100%"
          >
            <el-table-column
              prop="dateStr"
              label="时间"
              width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="epowerJsd" label="尖(kWh)" align="right">
            </el-table-column>
            <el-table-column prop="epowerFsd" label="峰(kWh)" align="right">
            </el-table-column>
            <el-table-column prop="epowerPsd" label="平(kWh)" align="right">
            </el-table-column>
            <el-table-column prop="epowerGsd" label="谷(kWh)" align="right">
            </el-table-column>
            <el-table-column
              prop="epowerTotal"
              label="总电量(kWh)"
              align="right"
              width="120"
            >
            </el-table-column>
            <el-table-column prop="fgPercent" label="尖峰占比" align="right">
              <template #default="{ row }">
                <span>{{
                  row.fgPercent ? (+row.fgPercent).toFixed(2) : '-'
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="degreeCharge"
              label="电度电费(元)"
              align="right"
              width="120"
            >
              <template #default="{ row }">
                <span>{{ (+row.degreeCharge).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="avgPrice"
              label="平均电价(元/kWh)"
              align="right"
              width="150"
            >
              <template #default="{ row }">
                <span>{{
                  row.avgPrice ? (+row.avgPrice).toFixed(2) : '-'
                }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import { getuserlistapi, getdianfenxiapi, postdaochuapi } from '@/api/analysis'
import * as echarts from 'echarts'
export default {
  name: 'CallPoliceIndex',
  data() {
    return {
      iissize: 'medium',
      orgName: '',
      form: { periodType: '月', value2: '', value3: '', orgNo: '' },
      qiyelist: [],
      tableData: [],
      tablelist: [],
      loading: false,
      epowerJsdlist: [],
      epowerFsdlist: [],
      epowerPsdlist: [],
      epowerGsdlist: [],
      bingtulist: [],
      junlist: [],
      dateStrlist: [],
      arrtotal:{}
    }
  },
  async mounted() {
    const res = await getuserlistapi()
    this.qiyelist = res.data.list
    this.form.orgNo = this.$store.state.statistics.userbizOrgNo
      ? this.$store.state.statistics.userbizOrgNo
      : res.data.list[0].bizOrgNo
    this.orgName = res.data.list[0].bizOrgName
    this.gettime()
    await this.getlist()
    this.fengzhuang(this.tablelist[this.tablelist.length-1])
    this.getbinecharts()
    this.getzduidiezhu()
  },

  methods: {
    // 获取用电量数据
    async getlist() {
      this.loading = true
      try {
        const res = await getdianfenxiapi({
          dateStr:
            this.form.periodType == '年' ? this.form.value3 : this.form.value2,
          orgNo: this.form.orgNo,
          periodType: this.form.periodType == '年' ? 'year' : 'month'
        })
        this.tablelist = res.data.list
        this.epowerJsdlist = res.data.list.map((ele) => ele.epowerJsd)
        this.epowerJsdlist.pop()
        this.epowerFsdlist = res.data.list.map((ele) => ele.epowerFsd)
        this.epowerFsdlist.pop()
        this.epowerPsdlist = res.data.list.map((ele) => ele.epowerPsd)
        this.epowerPsdlist.pop()
        this.epowerGsdlist = res.data.list.map((ele) => ele.epowerGsd)
        this.epowerGsdlist.pop()
        this.dateStrlist = res.data.list.map((ele) => ele.dateStr)
        this.dateStrlist.pop()
        this.tableData = res.data.list
        if (this.tableData.length == 0) {
          this.getzduidiezhu()
          this.bingtulist = []
          this.junlist = []
          this.getbinecharts()
        }
      } catch (error) {
        this.tablelist = []
        this.tableData = []
        this.dateStrlist = []
        this.epowerJsdlist = []
        this.epowerFsdlist = []
        this.epowerPsdlist = []
        this.epowerGsdlist = []
        this.getzduidiezhu()
        this.bingtulist = []
        this.junlist = []
        this.getbinecharts()
      }
      this.loading = false
    },
    // 表格点击获取饼图数据
    // handleCurrentChange(val) {
    //   this.fengzhuang(val)
    //   this.getbinecharts()
    // },
    fengzhuang(obj) {
      this.arrtotal=obj?obj:{}
      this.bingtulist = []
      this.junlist = []
      this.bingtulist.push({ value: obj.epowerJsd, name: '尖' })
      this.bingtulist.push({ value: obj.epowerFsd, name: '峰' })
      this.bingtulist.push({ value: obj.epowerPsd, name: '平' })
      this.bingtulist.push({ value: obj.epowerGsd, name: '谷' })
      this.junlist.push({ value: obj.avgPrice, name: '平均电价' })
    },
    // 获取当前时间戳
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      this.form.value3 = String(year)
      this.form.value2 = year + '-' + month
    },
    // 调节表格间隙
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    async submits() {
      await this.getlist()
      this.fengzhuang(this.tablelist[this.tablelist.length-1])
      this.getzduidiezhu()
      this.getbinecharts()
    },
    // 刷新列表
    shuaxin() {
      this.$message.success('列表刷新成功')
      this.submit()
    },
    change(val) {
      this.$store.commit('setuserobject', val)
      this.orgName = this.qiyelist.filter(
        (ele) => ele.bizOrgNo == val
      )[0].bizOrgName
    },
    // 导出
    async daochu() {
      const res = await postdaochuapi({
        dateStr:
          this.form.periodType == '年' ? this.form.value3 : this.form.value2,
        orgNo: this.form.orgNo,
        periodType: this.form.periodType == '年' ? 'year' : 'month',
        orgName: this.orgName,
        isParams: true
      })
      console.log(res)
      const blobContent = new Blob([res])
      const url = window.URL.createObjectURL(blobContent)
      saveAs(url, '单位电量分析.xls')
    },
    // 获取饼图图表
    getbinecharts() {
      const chartDom = this.$refs.binecharts
      const myChart = echarts.init(chartDom)
      let option
      const richColor = {}
      const pieColors = ['#ff6666', '#5996ff', '#18f2ce', '#ffbe4c']
      pieColors.forEach((item, idx) => {
        richColor[`color${idx}`] = {
          fontSize: 14,
          color: item
        }
      })
      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          data: ['尖', '峰', '平', '谷'],
          top: 'bottom'
        },
        color: pieColors,
        series: [
          {
            name: '平均电价',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            label: {
              position: 'center',
              formatter: '{c}\n{a}  ',
              fontSize: 14
            },
            labelLine: {
              show: false
            },
            data: this.junlist,
            color: ['green']
          },
          {
            name: '',
            type: 'pie',
            radius: ['45%', '60%'],
            labelLine: {
              length: 30
            },
            label: {
              // formatter: '{b} {d}% \n{c}(kwh) ',
              formatter: (params) => {
                return `{color${params.dataIndex}|${params.name}${params.percent}%\n${params.value}(kWh)}`
              },
              rich: richColor
            },
            // data: [
            //   { value: 1048, name: '尖' },
            //   { value: 335, name: '峰' },
            //   { value: 310, name: '平' },
            //   { value: 251, name: '谷' }
            // ]
            data: this.bingtulist
          }
        ]
      }

      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    },
    // 获取堆叠图图表
    getzduidiezhu() {
      const chartDom = this.$refs.zhuecharts
      const myChart = echarts.init(chartDom)
      let option
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        // legend: {},
        grid: {
          top: '%',
          left: '%',
          right: '%',
          bottom: '%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.dateStrlist
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '尖',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              normal: { color: '#ff6666' }
            },
            data: this.epowerJsdlist
          },
          {
            name: '峰',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              normal: { color: '#5996ff' }
            },
            data: this.epowerFsdlist
          },
          {
            name: '平',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              normal: { color: '#18f2ce' }
            },
            data: this.epowerPsdlist
          },
          {
            name: '谷',
            type: 'bar',
            stack: 'Ad',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              normal: { color: '#ffbe4c' }
            },
            data: this.epowerGsdlist
          }
        ]
      }

      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dengji {
  padding-left: 10px;
}
.bigbox {
  height: 100%;
  .titlebox {
    width: 100%;
    height: 80px;
    background-color: #fff;
    padding: 20px;
    margin-bottom: 10px;
  }
  .bodybox {
    background-color: #fff;
    // height:calc(100% - 90px);
    padding: 20px 20px 10px 20px;
    .title {
      text-align: right;
      .button {
        width: 60px;
        height: 30px;
        border: 1px solid #ccc;
        color: #fff;
        background-color: #1684fc;
        border-radius: 3px;
        margin-top: 5px;
      }
      .item {
        margin-left: 10px;
      }
    }
    .table {
      display: flex;
      .paiming{
        width: 60%;
        padding-left: 40px;
        padding: 30px 0 30px 20px;
        .item{
          display: flex;
          margin: 30px 0;
          justify-content: space-between;
          .itag{
            height: 80px;
            width: 48%;
            border-radius: 10px;
            padding: 0 20px;
            display: flex;
            align-items: center;
            .iconfont{
              font-size: 50px;
              color: #fff;
            }
            .icon{
              width: 20%;
            }
            .name{
              font-size: 18px;
              color: #fff;
              font-weight: 600;
            }
            .tabs{
              width: 25%;
            }
            .num{
              width: 55%;
            }
          }
          .jian{
            background-color: #ff6666;
          }
          .feng{
            background-color: #5996ff;
          }
          .ping{
            background-color: #18f2ce;
          }
          .gu{
            background-color: #ffbe4c;
          }
        }
      }
      .echarts {
        width: 40%;
        height: 300px;
      }
    }
    .zhuecharts {
      width: 100%;
      height: 300px;
      margin-top: 20px;
    }
    .biao {
      height: 300px;
    }
  }
}
::-webkit-scrollbar {
  display: none;
}
// ::v-deep .el-table__header-wrapper{
//   position: absolute;
//   // top: 0;
// }
// ::v-deep .el-table--enable-row-transition{
//   position: relative;
// }
// ::v-deep .el-table__body-wrapper{
//   margin-top: 60px;
// }
// ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
//   display: none;
//   // color: #acbac6;
// }
</style>
